package com.czf.testmodule.io.nio;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author zfChen
 * @create 2022/6/14 10:00
 */
public class ChannelTest {
    @Test
    public void write() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("src/main/java/com/czf/testmodule/io/nio/abc.txt");
            FileChannel channel = fileOutputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("hello!".getBytes());
            buffer.flip();
            channel.write(buffer);
            channel.close();
            System.out.println("写数据到文件中！");

            FileInputStream fileInputStream = new FileInputStream("src/main/java/com/czf/testmodule/io/nio/abc.txt");
            FileChannel channel1 = fileInputStream.getChannel();
            ByteBuffer buffer1 = ByteBuffer.allocate(1024);
            channel1.read(buffer1);
            buffer1.flip();
            String s = new String(buffer1.array(), 0, buffer1.remaining());
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
